package com.jcl.recruit.api.searchresume.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jcl.core.common.page.PageResult;
import com.jcl.core.resp.ApiResponse;
import com.jcl.recruit.core.web.utils.RequestUtils;
import com.jcl.recruit.searchresume.model.SearchResumeRecord;
import com.jcl.recruit.searchresume.service.SearchResumeRecordService;
import com.jcl.recruit.searchresume.vo.SearchResumeRecordVo;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

import static org.springframework.beans.support.PagedListHolder.DEFAULT_PAGE_SIZE;

@RestController
@RequestMapping("/api")
public class SearchResumeRecordController {

    @Autowired
    private SearchResumeRecordService searchResumeRecordService;

    @RequestMapping(value = "/searchresume/record/list", method = RequestMethod.GET)
    public ApiResponse list(@RequestParam(value = "page", required = false, defaultValue = "1") String toPage){

        PageHelper.startPage(Integer.valueOf(toPage), DEFAULT_PAGE_SIZE);
        Integer userId = Integer.parseInt(RequestUtils.getUserId());
        List<SearchResumeRecord> recordList = searchResumeRecordService.selectSearchResumeRecordByUserId(userId);
        PageInfo info = new PageInfo(recordList);
        PageResult result = new PageResult(Integer.valueOf(toPage), null, info.getTotal(), info.getList());
        return ApiResponse.success(result);
    }

    /**
     *
     * @param id
     * @return
     */
    @RequestMapping("/searchresume/record/find/{id}")
    public ApiResponse findOne(@PathVariable("id") String id){
        if(StringUtils.isBlank(id)){
            return ApiResponse.error("请求路径不合法！", null);
        }
        SearchResumeRecord record = searchResumeRecordService.selectSearchResumeRecordById(Integer.parseInt(id));
        return ApiResponse.success(record);
    }

    /**
     * 用户推荐记录新增
     * @param recordVo
     * @return
     */
    @RequestMapping(value = "/searchresume/record/add",method = RequestMethod.POST)
    public ApiResponse save(@RequestBody SearchResumeRecordVo recordVo){

        Integer userId = Integer.parseInt(RequestUtils.getUserId());
        List<SearchResumeRecord> oldRecordList = searchResumeRecordService.selectSearchResumeRecord(
                userId,  recordVo.getKeyword(), recordVo.getCity(), recordVo.getEducation(),
                recordVo.getWorkYear(), recordVo.getWechatPush(), recordVo.getEmailPush());
        if(CollectionUtils.isEmpty(oldRecordList)){
            SearchResumeRecord record = new SearchResumeRecord();
            try {
                PropertyUtils.copyProperties(record, recordVo);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
            record.setUserId(userId);
            record.setCreateTime(new Date());
            record.setUpdateTime(new Date());
            record.setKeyword(record.getKeyword().toLowerCase());
            SearchResumeRecord searchResumeRecord = searchResumeRecordService.selectPrimaryKeyByKeywordAndUpdatime(null,record.getKeyword());
            if(searchResumeRecord != null){
                record.setCrawingFrom(searchResumeRecord.getCrawingFrom());
            }
            searchResumeRecordService.insertSelective(record);
            return ApiResponse.success(record);
        }else{
            return ApiResponse.warning("系统已存在相同数据！");
        }
    }

    /**
     * 用户推荐记录修改
     * @param recordVo
     * @return
     */
    @RequestMapping(value = "/searchresume/record/update",method = RequestMethod.POST)
    public ApiResponse update(@RequestBody SearchResumeRecordVo recordVo){

        Integer userId = Integer.parseInt(RequestUtils.getUserId());
        List<SearchResumeRecord> oldRecordList = searchResumeRecordService.selectSearchResumeRecord(
                userId,  recordVo.getKeyword(), recordVo.getCity(), recordVo.getEducation(),
                recordVo.getWorkYear(), recordVo.getWechatPush(), recordVo.getEmailPush());
        if(CollectionUtils.isEmpty(oldRecordList)){
            SearchResumeRecord oldRecord = searchResumeRecordService.selectSearchResumeRecordById(recordVo.getId());
            if(null != oldRecord){
                try {
                    PropertyUtils.copyProperties(oldRecord, recordVo);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if(StringUtils.isNotBlank(oldRecord.getKeyword())) {
                    oldRecord.setKeyword(oldRecord.getKeyword().toLowerCase());
                    SearchResumeRecord searchResumeRecord = searchResumeRecordService.selectPrimaryKeyByKeywordAndUpdatime(null,oldRecord.getKeyword());
                    if(searchResumeRecord != null){
                        oldRecord.setCrawingFrom(searchResumeRecord.getCrawingFrom());
                    }
                }
                oldRecord.setUpdateTime(new Date());
                searchResumeRecordService.updateByPrimaryKeySelective(oldRecord);
                return ApiResponse.success(oldRecord);
            }else{
                return ApiResponse.error("修改数据不存在");
            }
        }else{
            return ApiResponse.warning("系统已存在相同数据！");
        }
    }

    /**
     * 假删除用户记录
     * @param id
     * @return
     */
    @RequestMapping("/searchresume/record/delete/{id}")
    public ApiResponse delete(@PathVariable("id") String id){
        if(StringUtils.isBlank(id)){
            return ApiResponse.error("请求路径不合法！");
        }
        int number = searchResumeRecordService.deleteSearchResumeRecordById(Integer.parseInt(id));
        return ApiResponse.success(number);
    }

    /**
     * 爬虫爬取的关键词接口
     * @param from
     * @return
     */
    @RequestMapping("/searchresume/keywords")
    public Map<String,Object> keywords(String from){
        Map<String,Object> map = new HashMap<>();
        String keyword = searchResumeRecordService.selectKeywordByCrawing(from);
        if(StringUtils.isNotBlank(keyword)) {
            List<SearchResumeRecord> list = searchResumeRecordService.selectListsByKeyword(keyword);
            Date date = new Date();
            for(SearchResumeRecord entity:list){
                entity.setUpdateTime(date);
                if(StringUtils.isBlank(entity.getCrawingFrom())){
                    entity.setCrawingFrom(from);
                }else{
                    entity.setCrawingFrom(entity.getCrawingFrom() + "|" + from);
                }
            }
            searchResumeRecordService.batchUpdate(list);
        }else{
            String keys = "\"python\", \"爬虫\", \"运营\", \"客服\", \"市场\", \"销售\", \"行政\", \"HR\", \"go\", \"spring\", \"vue\", \"react\", \"前端\", \"android\", \"ios\"";
            String[] kyeslist = keys.replaceAll("\"","").split(",");
            Random random = new Random();
            keyword = kyeslist[random.nextInt(14)].trim();
        }
        map.put("type","success");
        map.put("message","ok");
        map.put("keywords",keyword);
        return map;
    }
}
